using System;
using System.Collections.Generic;

namespace ZhiHeng.Consume.ServiceLib.DAL
{
    internal static class RepositoryFactory
    {
        static readonly Dictionary<string, IRepository> Cache = new Dictionary<string, IRepository>();
        static readonly object Root = new object();
        private const string DatacontractAssembly = "ZhiHeng.Consume.DataContract";
        private const string DatacontractNamespace = "ZhiHeng.Consume.DataContract";
        private const string TypeStringFormat = "{0}.{1},{2}";

        public static IRepository GetInstance(string t)
        {
            if (Cache.ContainsKey(t))
            {
                return Cache[t];
            }
            lock (Root)
            {
                Type rep = typeof(Repository<>);
                var typeName = string.Format(TypeStringFormat,DatacontractNamespace , t , DatacontractAssembly);
                Type supType = Type.GetType(typeName);
                Type[] typeArgs = { supType };
                Type makeme = rep.MakeGenericType(typeArgs);
                Cache[t] = (IRepository)Activator.CreateInstance(makeme);
            }
            return Cache[t];
        }
    }
}